const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const postSchema = new Schema({
  title: {
    type: String,
    required: true,
    trim: true,
    minlength: 2,
    maxlength: 100
  },
  content: {
    type: String,
    required: true,
    minlength: 10
  },
  user: {
    type: Schema.Types.ObjectId,
    ref: 'User',
    required: true
  },
  images: [{
    type: String // Store image URLs
  }],
  tags: [{
    type: String,
    trim: true
  }],
  likes: [{
    type: Schema.Types.ObjectId,
    ref: 'User'
  }],
  comments: [{
    type: Schema.Types.ObjectId,
    ref: 'Comment'
  }],
  category: {
    type: Schema.Types.ObjectId,
    ref: 'Category',
    required: true
  },
  views: {
    type: Number,
    default: 0
  },
  status: {
    type: String,
    enum: ['pending', 'approved', 'rejected'], 
    default: 'pending'
  },
  isDraft: {
    type: Boolean,
    default: false
  },
  isPinned: {
    type: Boolean,
    default: false 
  }
}, { timestamps: true });

// Add text index for searching title and content
postSchema.index({ title: 'text', content: 'text' });

// Method to increment views
postSchema.methods.incrementViews = async function() {
  this.views += 1;
  await this.save();
};

// Method to toggle like
postSchema.methods.toggleLike = async function(userId) {
  const index = this.likes.indexOf(userId);
  if (index === -1) {
    this.likes.push(userId);
  } else {
    this.likes.splice(index, 1);
  }
  await this.save();
  return this.likes.length;
};

const Post = mongoose.model('Post', postSchema);

module.exports = Post;